package com.capricornus.demo.service.user;

import java.util.List;
import java.util.Map;

import com.capricornus.demo.common.ApplicationException;
import com.capricornus.demo.common.util.PageRequest;
import com.capricornus.demo.common.util.PageResult;
import com.capricornus.demo.common.util.PageUtils;
import com.capricornus.demo.dao.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.capricornus.demo.model.User;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selectList(String userName, String realName) {
        return userMapper.selectList(userName, realName);
    }

    @Override
    public PageResult findPage(User user) {
        return PageUtils.getPageResult(user, getPageInfo(user));
    }

    /**
     * 调用分页插件完成分页
     *
     * @return
     */
    private PageInfo<User> getPageInfo(User user) {
        int pageNum = user.getPageNum();
        int pageSize = user.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<User> sysMenus = userMapper.selectPage(user.getUserName(), user.getRealName());
        return new PageInfo<User>(sysMenus);
    }

    @Override
    public int updateUserValidByUserId(String userId) {

        int updateCount = userMapper.updateUserValidByUserId(userId);
        if (updateCount < 1) {
            throw new ApplicationException("删除失败");
        }

        return updateCount;
    }

    @Override
    public User selectByPrimaryKey(String userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public int deleteByUserId(String userId) {

        int updateCount = userMapper.deleteByUserId(userId);
        if (updateCount < 1) {
            throw new ApplicationException("删除失败");
        }

        return updateCount;
    }

    @Override
    public boolean selectIsUserNameExist(String userName) {
        return userMapper.selectIsUserNameExist(userName);
    }

    @Override
    public int insert(User user) {

        int updateCount = userMapper.insert(user);
        if (updateCount <= 0) {
            throw new ApplicationException("用户新增失败");
        }

        return updateCount;
    }

    @Override
    public int update(User user) {

        int updateCount = userMapper.update(user);
        if (updateCount <= 0) {
            throw new ApplicationException("编辑用户失败");
        }

        return updateCount;
    }
}
